﻿/*
 * (c) Stefan Bojarovski 2010
 * */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ASTBuilder
{
    class GotoNode : NodesCollection, ITreeNode
    {
        private LexemeType lexType = LexemeType.GOTO;
        private IdentifierNode Label;

        public GotoNode(IdentifierNode someLabel)
        {
            Label = someLabel;
        }
        public LexemeType getLexemeType()
        {
            return lexType;
        }
        public void printNode(String parentLevel, StreamWriter someStream)
        {
            someStream.WriteLine(parentLevel + " " + "GOTO: ");
            someStream.Write(parentLevel + "  ");
            Label.printNode(parentLevel + "  ", someStream);
        }
        public List<Command> evalNode(ref Direction next,
                                        ref Dictionary<String, Pair<IdentifierType, object>> Environment)
        {
            List<Command> gotoRes = new List<Command>();
            if (next != Direction.JUMP)
            {
                String jumpToLabel = Label.evalNode(ref next, ref Environment)[0].getIdName();

                if ((Environment.ContainsKey(jumpToLabel))
                    && (Environment[jumpToLabel].getLeft() == IdentifierType.LABEL))
                {
                    gotoRes.Add(new Command(CommandType.FLOWCONTROLL, jumpToLabel, null));
                    next = Direction.JUMP;
                    return gotoRes;
                }
                else
                {
                    gotoRes.Add(new Command(CommandType.ERRORNOSUCHID, jumpToLabel, null));
                    return gotoRes;
                }
            }
            else 
            {
                gotoRes.Add(new Command(CommandType.VOID, null, null));
                return gotoRes;
            }
        }
    }
}
